﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using FirstFloor.ModernUI.Windows.Controls;
using YanMsg.APCode;


namespace YanMsg.View
{
    /// <summary>
    /// MsgBox.xaml 的交互逻辑
    /// </summary>
    public partial class MsgBox : ModernWindow
    {

        public static ObservableCollection<YanChat_UserMsg> ListNotice = new ObservableCollection<YanChat_UserMsg>();
        private static ObservableCollection<YanChat_File> ListFiles = new ObservableCollection<YanChat_File>();
        public MsgBox()
        {
            InitializeComponent();
            this.Style = (Style)App.Current.Resources["EmptyWindow"];
            ListMsgIndex.ItemsSource = ListNotice;
            Refresh();
            BindListData("0");
        }



        private void Refresh()
        {
            if (TBYDXX!=null)
            {
                TBYDXX.Text = "(" + new YanChat_UserMsgB().GetEntitiesCount("MsgUser='" + UserData.UserNumber + "' AND MsgIsRead='1'").ToString() + ")";
                TBZYXX.Text = "(" + new YanChat_UserMsgB().GetEntitiesCount("MsgUser='" + UserData.UserNumber + "' AND MsgType='1'").ToString() + ")";
                TBYFXX.Text = "(" + new YanChat_UserMsgB().GetEntities(" cruser='" + UserData.UserNumber + "'").Select(d => d.MsgID).Distinct().Count() + ")";
                TBWDXX.Text = "(" + new YanChat_UserMsgB().GetEntitiesCount("MsgUser='" + UserData.UserNumber + "' AND MsgIsRead='0'").ToString() + ")";
            }

        }
        private void AddMsg_Click(object sender, RoutedEventArgs e)
        {
            AddMsg newmsg = new AddMsg();
            MsgManger.ShowWindows(newmsg);
        }
        private void Reflesh_Click(object sender, RoutedEventArgs e)
        {
            Refresh();
        }

        

        /// <summary>
        /// 根据通知类别查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
          
            string NoticeType = ((ListBoxItem)ListType.SelectedItem).Tag == null ? "0" : ((ListBoxItem)ListType.SelectedItem).Tag.ToString();
            BindListData(NoticeType);
            Refresh();
        }


        //
        private void ImageSetSC_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string NoticeID = ((Image)sender).Tag.ToString();
            ListNotice.SingleOrDefault(d => d.id.ToString() == NoticeID).MsgType = ListNotice.SingleOrDefault(d => d.id.ToString() == NoticeID).MsgType == "0" ? "1" : "0";
            e.Handled = true;
            Task task = new Task(UpdateNoticeType, NoticeID);
            task.Start();

        }

        public void UpdateNoticeType(object NoticeID)
        {
            this.Dispatcher.Invoke(new Action(() =>
           {
               YanChat_UserMsg UpItem = ListNotice.SingleOrDefault(d => d.id.ToString() == NoticeID.ToString());
               new YanChat_UserMsgB().Update(UpItem);
           }));
        }

        private void ListMsgIndex_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            YanChat_UserMsg Notice = (YanChat_UserMsg)ListMsgIndex.SelectedItem;
            if (Notice!=null)
            {
                string MsgId = Notice.MsgID;
                YanChat_MsgContent Msg = new YanMsg.APCode.YanChat_MsgContentB().GetEntity(d => d.id.ToString() == MsgId);
                TBMsgTitle.Text = Msg.MSGTitle;
                TBMsgDec.Text = "发送人:" + ChatManger.GetUserName(Msg.MSGCRPeople) + "   发送时间:" + Msg.MSGCRDate.ToString();

                //如果是自己发的消息，显示删除按钮
                if (Msg.MSGCRPeople==UserData.UserNumber)
                {
                    btDelTZ.Visibility = Visibility.Visible;
                    btDelTZ.Tag = Msg.id.ToString();
                }
                ChatManger.LoadFromRTF(ConMsgContent, Msg.MSGContent);

                    Task task = new Task(new Action(() =>
                    {
                        this.Dispatcher.Invoke(new Action(() =>
                       {
                           if (Notice.MsgIsRead == "0")
                           {
                               Notice.MsgIsRead = "1";
                               new YanChat_UserMsgB().Update(Notice);
                           }
                           ListFiles = new YanChat_FileB().GetEntities(" GGID='" + MsgId + "'").ToList().ToObservableCollection();
                           ConFileList.ItemsSource = ListFiles;

                       }));
                    }));
                    task.Start();
            }
        }

        private void ConFileList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                YanChat_File File = ConFileList.SelectedItem as YanChat_File;
                if (File != null)
                {
                    SaveFileDialog saveFileDialog = new SaveFileDialog();
                    saveFileDialog.Filter = "所有文件|*.*";
                    saveFileDialog.FilterIndex = 1;
                    saveFileDialog.RestoreDirectory = true;
                    saveFileDialog.FileName = File.FileName;
                    if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        string fName = saveFileDialog.FileName;
                        Byte[] FileByte = File.FileContent;
                        MemoryStream MFile = new MemoryStream(FileByte);
                        FileStream fs = new FileStream(fName, FileMode.OpenOrCreate);
                        MFile.WriteTo(fs);
                        MFile.Close();
                        fs.Close();
                        MFile = null;
                        fs = null;
                        MsgManger.Show("下载完成");
                    }
                }



            }
            catch (Exception)
            {
                MsgManger.Show("服务器链接失败，请稍后再试！");
            }
        }

        private void btDelTZ_Click(object sender, RoutedEventArgs e)
        {
            var result = ModernDialog.ShowMessage("确认要删除该消息", "提示", MessageBoxButton.YesNo);
            //确定后删除该消息
            if (result.ToString() == "Yes")
            {
                int MsgID = int.Parse(btDelTZ.Tag.ToString());
                new YanChat_UserMsgB().Delete(d => d.MsgID == MsgID.ToString());
                new YanChat_MsgContentB().Delete(d => d.id == MsgID);
                new YanChat_FileB().Delete(d => d.GGID == MsgID.ToString());
            }

            Refresh();
            BindListData("0");
            btDelTZ.Visibility = Visibility.Hidden;
            ListFiles.Clear();
        }



        private void BindListData(string NoticeType)
        {
            ListNotice.Clear();
            if (NoticeType == "0")
            {
                foreach (var item in new YanChat_UserMsgB().GetEntitiesTop(1000, " MsgUser='" + UserData.UserNumber + "' AND MsgIsRead='0'").OrderByDescending(d => d.crdate))
                {
                    ListNotice.Add(item);
                }
            }
            if (NoticeType == "1")
            {
                foreach (var item in new YanChat_UserMsgB().GetEntitiesTop(1000, " MsgUser='" + UserData.UserNumber + "' AND MsgIsRead='1'").OrderByDescending(d => d.crdate))
                {
                    ListNotice.Add(item);
                }

            }
            if (NoticeType == "2")
            {
                foreach (var item in new YanChat_UserMsgB().GetEntitiesTop(1000, " MsgUser='" + UserData.UserNumber + "' AND MsgType='1' ").OrderByDescending(d => d.crdate))
                {
                    ListNotice.Add(item);
                }
            }
            if (NoticeType == "3")//已发消息
            {
                foreach (var item in new YanChat_UserMsgB().GetEntitiesTop(1000, " cruser='" + UserData.UserNumber + " ' ").OrderByDescending(d => d.crdate))
                {
                    if (ListNotice.Where(d => d.MsgID == item.MsgID).Count() == 0)
                    {
                        ListNotice.Add(item);
                    }
                }
            }
        }
    }    
}
